
#****************************************************************************************************
# File Start!
#***************************************************************************************************/

#*
 #
 #  Copyright (c) 2024-2025 by flechazo. All rights reserved.
 #
 # Author : CarlChai LinFeng Chai flechazo
 # Website: flechazo.mba
 #
 # Change Logs:
 # Date           Author       Notes
 # 2025-06-17     cc          the first version
 #
#/

#****************************************************************************************************
# Include
#***************************************************************************************************/

# ui #
import tkinter as tk
from tkinter import ttk, messagebox
# database #
from database.database import database_config_get,database_keys_get,database_actions_get,database_system_shortcut_get,database_user_shortcut_get
# command #
from command.command import command_init,command_table_get,command_add,command_del

#****************************************************************************************************
# Define
#***************************************************************************************************/

#****************************************************************************************************
# Type Define
#***************************************************************************************************/

#****************************************************************************************************
# Global Variable
#***************************************************************************************************/

global_display_user_ui = {
    "table_treeview":None,
    "keys_combobox":None,
    "actions_combobox":None,
    "reference_notebook":None,
    "reference_keys":None,
    "reference_actions":None,
    "reference_keys_notebook":None,
    "reference_actions_notebook":None,
    "operate_frame":None,
    "reference_paned":None,
    "reference_frame":None,
    "user_frame":None,
    "root":None,
}

#****************************************************************************************************
# Function Impletement
#***************************************************************************************************/

#****************************************************************************************************
# display_ui_user_shortcut_table_show()
#***************************************************************************************************/
def display_ui_user_shortcut_table_show(table_treeview):
    # get user config #
    shortcuts = command_table_get()
    # clear #
    for item in table_treeview.get_children():
        table_treeview.delete(item)
    # add #
    for shortcut in shortcuts:
        key = shortcut['keys']
        action = shortcut['actions']
        table_treeview.insert("", tk.END, values=(key, action))

#****************************************************************************************************
# display_ui_user_shortcut_table_init()
#***************************************************************************************************/
def display_ui_user_shortcut_table_init(table_frame):
    # tree view #
    columns = ("shortcut", "action")
    table_treeview = ttk.Treeview(table_frame, columns=columns, show="headings")
    for col in columns:
        table_treeview.heading(col, text=col)
        table_treeview.column(col, width=100)
    table_treeview.grid(row=0, column=0,columnspan=9, sticky=(tk.W, tk.E, tk.N, tk.S))
    # scrollbar #
    scrollbar = ttk.Scrollbar(table_frame, orient=tk.VERTICAL, command=table_treeview.yview)
    scrollbar.grid(row=0, column=10, sticky=(tk.N, tk.S))
    table_treeview.configure(yscrollcommand=scrollbar.set)
    global_display_user_ui["table_treeview"] = table_treeview
    return True

#****************************************************************************************************
# display_ui_user_shortcut_reference_combobox_append()
#***************************************************************************************************/
def display_ui_user_shortcut_reference_combobox_append(value,inputbox):
    # get input #
    current = inputbox.get()
    if current:
        # append #
        inputbox.delete(0, tk.END)
        inputbox.insert(0, f"{current}+{value}")
    else:
        # add #
        inputbox.insert(0, value)

#****************************************************************************************************
# display_ui_user_shortcut_reference_keys_init()
#***************************************************************************************************/
def display_ui_user_shortcut_reference_keys_init(notebook,categories):
    # reference keys table init #
    for category, keys in categories.items():
        # frame #
        frame = ttk.Frame(notebook, padding="5")
        notebook.add(frame, text=category)
        # grid #
        row = 0
        col = 0
        max_cols = 8
        # foreach keys #
        for key in keys:
            # create btn #
            btn = ttk.Button(frame, text=key, width=8,
                            command=lambda k=key: display_ui_user_shortcut_reference_combobox_append(k,global_display_user_ui["keys_combobox"]))
            btn.grid(row=row, column=col, padx=2, pady=2)
            col += 1
            # check cols num #
            if col >= max_cols:
                col = 0
                row += 1

#****************************************************************************************************
# display_ui_user_shortcut_reference_actions_init()
#***************************************************************************************************/
def display_ui_user_shortcut_reference_actions_init(notebook,categories):
    # reference actions table init #
    for category, actions in categories.items():
        # frame #
        frame = ttk.Frame(notebook, padding="5")
        notebook.add(frame, text=category)
        # grid #
        row = 0
        col = 0
        max_cols = 6
        # foreach actions #
        for action in actions:
            # create btn #
            btn = ttk.Button(frame, text=action["name"], width=10,
                            command=lambda k=action["name"]: display_ui_user_shortcut_reference_combobox_append(k,global_display_user_ui["actions_combobox"]))
            btn.grid(row=row, column=col, padx=2, pady=2)
            col += 1
            # check cols num #
            if col >= max_cols:
                col = 0
                row += 1

#****************************************************************************************************
# display_ui_user_shortcut_operate_keys_combobox_init()
#***************************************************************************************************/
def display_ui_user_shortcut_reference_init(reference_frame):

    # tag #
    reference_notebook = ttk.Notebook(reference_frame)
    reference_notebook.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
    reference_notebook.columnconfigure(0, weight=1)
    reference_notebook.rowconfigure(0, weight=1)
    global_display_user_ui["reference_notebook"] = reference_notebook
    # keys #
    reference_keys = ttk.Frame(reference_notebook, padding="10")
    reference_keys.columnconfigure(0, weight=1)
    reference_keys.rowconfigure(0, weight=1)
    reference_notebook.add(reference_keys, text="reference keys")
    global_display_user_ui["reference_keys"] = reference_keys
    # actions #
    reference_actions = ttk.Frame(reference_notebook, padding="10")
    reference_actions.columnconfigure(0, weight=1)
    reference_actions.rowconfigure(0, weight=1)
    reference_notebook.add(reference_actions, text="reference actions")
    global_display_user_ui["reference_actions"] = reference_actions
    # key table #
    keys = database_keys_get()
    actions = database_actions_get()
    # reference keys categories #
    reference_keys_notebook = ttk.Notebook(reference_keys)
    reference_keys_notebook.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
    reference_keys_notebook.columnconfigure(0, weight=1)
    reference_keys_notebook.rowconfigure(0, weight=1)
    global_display_user_ui["reference_keys_notebook"] = reference_keys_notebook
    display_ui_user_shortcut_reference_keys_init(reference_keys_notebook,keys)
    # action table #
    reference_actions_notebook = ttk.Notebook(reference_actions)
    reference_actions_notebook.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
    reference_actions_notebook.columnconfigure(0, weight=1)
    reference_actions_notebook.rowconfigure(0, weight=1)
    global_display_user_ui["reference_actions_notebook"] = reference_actions_notebook
    display_ui_user_shortcut_reference_actions_init(reference_actions_notebook,actions)

    return True

#****************************************************************************************************
# display_ui_user_shortcut_operate_keys_combobox_init()
#***************************************************************************************************/
def display_ui_user_shortcut_operate_keys_combobox_init(combobox):
    # get database #
    keys = database_keys_get()
    key_list = [item for sublist in keys.values() for item in sublist]
    combobox['values'] = [''] + sorted(key_list)
    return True

#****************************************************************************************************
# display_ui_user_shortcut_operate_keys_init()
#***************************************************************************************************/
def display_ui_user_shortcut_operate_keys_init(parent):
    ttk.Label(parent, text="keys:").grid(row=0, column=0, padx=1)
    keys_var = tk.StringVar()
    keys_combobox = ttk.Combobox(parent, textvariable=keys_var, width=15)
    keys_combobox.grid(row=0, column=1, padx=1)
    global_display_user_ui["keys_combobox"] = keys_combobox
    # fill #
    display_ui_user_shortcut_operate_keys_combobox_init(keys_combobox)
    return True

#****************************************************************************************************
# display_ui_user_shortcut_operate_actions_combobox_init()
#***************************************************************************************************/
def display_ui_user_shortcut_operate_actions_combobox_init(combobox):
    actions = database_actions_get()
    action_list = [item['name'] for category in actions.values() for item in category]
    combobox['values'] = [''] + sorted(action_list)
    return True

#****************************************************************************************************
# display_ui_user_shortcut_operate_actions_init()
#***************************************************************************************************/
def display_ui_user_shortcut_operate_actions_init(parent):
    ttk.Label(parent, text="actions:").grid(row=0, column=3, padx=1)
    actions_var = tk.StringVar()
    actions_combobox = ttk.Combobox(parent, textvariable=actions_var, width=15)
    actions_combobox.grid(row=0, column=4, padx=1)
    global_display_user_ui["actions_combobox"] = actions_combobox
    # fill #
    display_ui_user_shortcut_operate_actions_combobox_init(actions_combobox)
    return True

#****************************************************************************************************
# display_ui_user_shortcut_operate_init()
#***************************************************************************************************/
def display_ui_user_shortcut_operate_add():
    # get #
    shortcut = global_display_user_ui["keys_combobox"].get().strip()
    action = global_display_user_ui["actions_combobox"].get().strip()
    # check #
    if not shortcut or not action:
        messagebox.showerror("error", "keys | actions is null...")
        return
    # add #
    if command_add(shortcut, action):
        display_ui_user_shortcut_table_show(global_display_user_ui["table_treeview"])
        global_display_user_ui["keys_combobox"].set('')
        global_display_user_ui["actions_combobox"].set('')
    else:
        messagebox.showerror("error", "add shortcut fail")
    return
    
#****************************************************************************************************
# display_ui_user_shortcut_operate_init()
#***************************************************************************************************/
def display_ui_user_shortcut_operate_del():
    # get selected #
    selected = global_display_user_ui["table_treeview"].selection()
    if not selected:
        return
    for itemid in selected:
        # get #
        item = global_display_user_ui["table_treeview"].item(itemid)
        print(f"[info] delete:{item['values']}")
        # del #
        command_del(item["values"][0],item["values"][1])
    # show #
    display_ui_user_shortcut_table_show(global_display_user_ui["table_treeview"])
    return

#****************************************************************************************************
# display_ui_user_shortcut_operate_init()
#***************************************************************************************************/
def display_ui_user_shortcut_operate_init(parent):
    # keys #
    display_ui_user_shortcut_operate_keys_init(parent)
    # actions #
    display_ui_user_shortcut_operate_actions_init(parent)
    # add sortcut #
    ttk.Button(parent, text="add", command=display_ui_user_shortcut_operate_add).grid(row=0, column=5, padx=5,sticky=tk.W)
    # del sortcut #
    ttk.Button(parent, text="del", command=display_ui_user_shortcut_operate_del).grid(row=0, column=6, padx=5,sticky=tk.W)
    pass

#****************************************************************************************************
# display_ui_user_shortcut_init()
#***************************************************************************************************/
def display_ui_user_shortcut_init(parent):
    # operate #
    operate_frame = ttk.LabelFrame(parent, text="add shortcut", padding="5")
    operate_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
    operate_frame.columnconfigure(0, weight=1)
    operate_frame.rowconfigure(0, weight=1)
    global_display_user_ui["operate_frame"] = operate_frame
    display_ui_user_shortcut_operate_init(operate_frame)

    # reference #
    # paned #
    reference_paned = ttk.PanedWindow(parent, orient=tk.VERTICAL)
    reference_paned.grid(row=2, column=0, columnspan=10, sticky=(tk.W, tk.E, tk.N, tk.S), pady=5)
    reference_paned.columnconfigure(0, weight=1)
    reference_paned.rowconfigure(2, weight=1)
    global_display_user_ui["reference_paned"] = reference_paned
    # frame #
    reference_frame = ttk.Frame(reference_paned, padding="10")
    reference_frame.grid(row=0, column=0, columnspan=10,sticky=(tk.W, tk.E, tk.N, tk.S))
    reference_frame.columnconfigure(0, weight=1)
    reference_frame.rowconfigure(0, weight=1)
    reference_paned.add(reference_frame, weight=1)
    global_display_user_ui["reference_frame"] = reference_frame
    display_ui_user_shortcut_reference_init(reference_frame)

    # shortcut table #
    shortcuttable_frame = ttk.LabelFrame(reference_paned, text="current shortcut table", padding="5")
    shortcuttable_frame.grid(row=12, column=0, rowspan=10, columnspan=10,sticky=(tk.W, tk.E, tk.N, tk.S), pady=10)
    shortcuttable_frame.columnconfigure(0, weight=1)
    shortcuttable_frame.rowconfigure(12, weight=1)
    reference_paned.add(shortcuttable_frame, weight=1)
    global_display_user_ui["shortcuttable_frame"] = shortcuttable_frame
    display_ui_user_shortcut_table_init(shortcuttable_frame)
    display_ui_user_shortcut_table_show(global_display_user_ui["table_treeview"])
    return True

#****************************************************************************************************
# display_ui_user_init()
#***************************************************************************************************/
def display_ui_user_init(parent):
    # global #
    global_display_user_ui["root"] = parent
    # user ui init #
    user_frame = ttk.Frame(parent, padding="10")
    user_frame.columnconfigure(0, weight=1)
    user_frame.rowconfigure(0, weight=1)
    parent.add(user_frame, text="user shortcut configure")
    global_display_user_ui["user_frame"] = user_frame
    # user shortcut config #
    display_ui_user_shortcut_init(user_frame)
    return user_frame


#****************************************************************************************************
# exports
#***************************************************************************************************/

#****************************************************************************************************
# File End!
#***************************************************************************************************/
